import React from 'react'
import {connect} from 'react-redux'
import { Tabs, Modal, Row ,Col, Spin, Popover, message } from 'antd';
const TabPane = Tabs.TabPane;
import repaymentContent from "containers/loan-billing/template/repayment-content";
import {dealCache, deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import viewLine from "containers/loan-billing/template/view-line";
import SearchArea from 'components/search-area';
import borrowService from "./borrow-and-return.service";
import SlideFrame from 'components/slide-frame';
import moment from "moment/moment";
import configureStore from "stores";
import menuRoute from "routes/menuRoute";
import {setLoanSearch} from "actions/cache";
import ResizeTable from 'components/resize-table';
import refundContent from "containers/loan-billing/template/refund-content";
import ViewHistory from "containers/loan-billing/template/view-history";
import extendLoad from 'containers/loan-billing/template/extend-load';
import turnPermanent from 'containers/loan-billing/template/turn-permanent';
import AgentModal from 'containers/my-account/didi-expense/agent-modal';
import DiDiService from 'containers/my-account/didi-expense/didi-expense.service';
let cacheSearchData = {};

class LoanManagement extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      status: 'my-borrow', //tab的状态
      tabs: [
        {key: 'my-borrow', name: messages('loan-billing.key43')/*我的待还款*/},
        {key: 'other-borrow', name: messages('loan-billing.key44')/*其他待还款*/}
      ],
      searchForm: [
        {
          type: 'input',
          id: 'keyWord',
          label: messages('loan-billing.key45')/*收款人*/,
          placeholder: messages('loan-billing.key46')/*请输入姓名／工号*/
        },
        {
          type: 'select', id: 'currencyCode', label: messages('common.currency'), options: [],
          getUrl: `/api/currency/status/query/by/setOfBooksId?userOId=${props.user.userOID}`,
          labelKey: 'currency', valueKey: 'currency', method: 'get'
        },
        {
          type: 'combobox',
          id: 'companyId',
          label: messages('loan-billing.key48')/*公司*/,
          placeholder: messages('loan-billing.key49')/*请输入公司名称*/,
          options: [],
          searchUrl: `/api/refactor/companies/user/setOfBooks?userOID=${configureStore.store.getState().login.user.userOID}&enabled=true&page=0&size=1000`,
          method: 'get',
          searchKey: 'name',
          labelKey: 'name',
          valueKey: 'id'
        },
        {
          type: 'combobox', id: 'businessCode', label: messages('loan-billing.key117')/*借款单号*/,
          placeholder: messages('common.please.enter') + messages('loan-billing.key117')/*借款单号*/,
          options: [],
          searchUrl: `/api/loanBill/query/business/code/by/keyword`,
          method: 'get',
          searchKey: 'keyword', getParams: {status: 'prending_pay'}, labelKey: '_self', valueKey: '_self'
        },
        {
          type: 'input', id: 'remark', label: messages('loan-billing.key119')/*事由*/
        },
        {
          type: 'radio', label: messages('loan-billing.key50')/*还款状态*/, id: 'statusEnums', event: 'STATUS_CHANGE',
          options: [{label: messages('common.all'), value: 'default'},
            {label: messages('loan-billing.key51')/*有欠款*/, value: 'A_1006'},
            {label: messages('loan-billing.key9')/*已还款*/, value: 'A_1007'}
          ],
          defaultValue: 'default'
        }
      ],
      searchParams: {isProxy: false},
      data: [],
      page: 0,
      size: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      columns: [
        {title: messages('common.document.code')/*单号*/,dataIndex: 'businessCode', render: (value,record) => <a onClick={(e) => this.handleRowClick(e,record)}>{value}</a>},
        {title: messages('loan-billing.key52')/*借款公司*/,dataIndex: 'companyName'},
        {title: messages('loan-billing.key53')/*申请人/代理人*/,dataIndex: 'ownerName',render: (value, record) => record.ownerOid === record.createdBy ? value : `${value}/${record.createdByName}`},
        { title: messages('loan-billing.key12')/*借款类型*/, dataIndex: 'loanTypeName', render: value => <Popover placement={'topLeft'} content={value}>{value}</Popover> },
        {title: messages('loan-billing.key119')/*事由*/,dataIndex: 'remark'},
        {title: messages('common.date')/*日期*/, dataIndex: 'createdDate',width: 120, render: (value) => moment(value).format('YYYY-MM-DD')},
        {title: messages('loan-billing.key45')/*收款人*/,dataIndex: 'payeeName'},
        {title: messages('common.currency')/*币种*/,dataIndex: 'currencyCode'},
        {title: messages('loan-billing.key54')/*待还款金额*/,dataIndex: 'stayWriteoffAmount', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('loan-billing.key90')/*还款中金额*/,dataIndex: 'lockedWriteoffAmount', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('loan-billing.key55')/*已还款金额*/,dataIndex: 'hasWriteoffAmount', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('common.operation')/*操作*/, width: 150, dataIndex: 'operator', render: (value, record) => {
          return <div style={{ display: 'flex' }}>
            <div>
              {record.stayWriteoffAmount > 0 && !record.creditLocked && this.checkFunctionProfiles(['finance.cash.repaymemt.disabled'], [[false, undefined]])
                && <div>
                  <a onClick={e => this.handleRepayment(e, record)}>{messages('loan-billing.key42')/*新建还款*/}</a>
                </div>
              }
              <a onClick={e => this.handleViewHistory(e,record)}>{messages('loan-billing.key121')/*还款历史*/}</a>
            </div>
            {record.formCode === 'JK004' && record.stayWriteoffAmount > 0 && !record.creditLocked && this.checkFunctionProfiles(['finance.cash.repaymemt.disabled'], [[false, undefined]]) ? <div style={{ display: 'flex', flexDirection: 'column', marginLeft: 10 }}>
              <a onClick={(e) => this.extendMoney(e, value, record)}>{messages('financial-management.key1239', /*延长还款*/)}</a>
              <a onClick={(e) => this.turnPermanent(e, value, record)}>{messages('financial-management.key1240', /*转永久*/)}</a>
            </div> : ''}
          </div>
          }}
      ],
      loading: false,
      repayFrame: false,
      loanDetail: menuRoute.getRouteItem('line-loan-detail'),
      info: {},
      modalShow: false,
      allLoading: false,
      transactionList: [],
      transactionColumns: [
        {title: messages('loan-billing.key111')/*交易日期*/, dataIndex: 'createdDate', render: value =>  moment(value).format('YYYY-MM-DD')},
        {title: messages('loan-billing.key112')/*付款流水号*/, dataIndex: 'transactionDetailCode', render: value => <Popover placement={'topLeft'} content={value}>{value}</Popover>},
        {title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 72},
        {title: messages('common.total.amount')/*总金额*/, dataIndex: 'amount', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('loan-billing.key113')/*可还款金额*/, dataIndex: 'repaymentValue', render: (value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))}
      ],
      editTransaction: {},
      historyModal: false,
      historyId: '',
      viewFrame: false,
      viewId: '',
      rowSelection: {
        type: 'radio',
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem
      },
      refundFrame: false,
      refundParams: '',
      extendMoneyFrame: false,
      turnPermanentFrame: false,
      agendVisible: false,
      dataList: [],
      agentUser: undefined
    }
  }

  componentWillMount() {
    let result = this.props.loanSearch;
    if(result && JSON.stringify(result) !== "{}"){
      cacheSearchData = result;
      this.dealCache(result);
    }
    else{
      this.getListData();
      // this.getList();
    }
  }

  getListData = async () => {
    const data = await DiDiService.getProxyPrincipals();
    if (data.status === 200) {
      if (data.data && data.data.length > 0) {
        this.setState({
          agendVisible: true,
          dataList: data.data
        })
      } else {
        this.setState({
          agendVisible: false
        }, () => {
          this.getList();
        })
      }
    }
  }

  handleRepayment = (e, record) => {
    e.stopPropagation();
    this.setState({allLoading: true});
    borrowService.getTransactionList(record.id).then(res => {
      if(res.data.length === 0){
        message.error(messages('loan-billing.key114')/*该借款行无支付流水*/);
        this.setState({allLoading: false});
        return -1;
      }
      let temp = {
        allLoading: false,
        transactionList: res.data
      };
      res.data.length > 1 ? (temp.modalShow = true) : (temp.repayFrame = true);
      let infoRecord = deepFullCopy(record);
      infoRecord.stayWriteoffAmount = res.data[0].repaymentValue;
      infoRecord.transactionDetailId = res.data[0].transactionDetailId;
      infoRecord.transactionDetailCode = res.data[0].transactionDetailCode;
      this.setState({info: infoRecord},() => {
        this.setState(temp);
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({allLoading: false});
    })
  };

  handleViewHistory = (e,record) => {
    e.stopPropagation();
    this.setState({ historyId: record.id }, () => this.setState({ historyModal: true }));
  };

  dealCache = (result) => {
    let { status, searchForm, page } = this.state;
    if (result) {
      status = result.status;
      page = result.page;
      dealCache(searchForm, result);
      this.setState({status, searchForm, page}, () => {
        this.search(result);
        configureStore.store.dispatch(setLoanSearch(null));
      })
    }
  };

  getList = () => {
    const { searchParams, page, size, pagination, agentUser } = this.state;
    this.setState({loading:true});
    let userOID = this.props.user.userOID;
    if (agentUser) {
      userOID = agentUser.userOID;
      // searchParams.isProxy = true;
    }
    searchParams.page = page;
    borrowService.getTableLine(searchParams,userOID,size).then(res => {
      pagination.total = res.data.total || 0;
      pagination.current = page + 1;
      pagination.onChange = this.onChangePaper;
      this.setState({
        data: res.data.rows,
        loading: false,
        pagination
      })
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading:false});
    });
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.size)
      this.setState({
        page: 0,
        size: size
      },() => {
        this.getList()
      })
  };

  //分页
  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getList()
      })
    }
  };

  //tab切换
  onChangeTabs = (value) => {
    let search = {};
    search.isProxy = value === 'other-borrow';
    this.setState({
      searchParams: search,
      page: 0,
      status: value
    },() => {
      const { searchParams, status, page } = this.state;
      let result = deepFullCopy(searchParams);
      result.status = status;
      result.page = page;
      cacheSearchData = result;
      this.searchTag && this.searchTag.setValues({
        keyWord: '',
        currencyCode: '',
        companyId: '',
        remark: '',
        businessCode: '',
        statusEnums: 'default',
      });
      this.getList();
    })
  };

  //渲染tabs
  renderTabs = () => {
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key}/>;
      })
    )
  };

  //搜索
  search = (values) => {
    const { status,page } = this.state;
    let result = deepFullCopy(values);
    result.status = status;
    result.page = page;
    cacheSearchData = result;
    values.isProxy = status === 'other-borrow';
    values.statusEnums && (values.statusEnums = (values.statusEnums === 'A_1006' ? ['PAID','A_1006'] : (values.statusEnums === 'default' ? null : values.statusEnums)));
    this.setState({searchParams: values, page: 0},() => {
      this.getList();
    })
  };

  //清楚搜索
  clear = () => {
    const { status } = this.state;
    let temp = status === 'other-borrow';
    this.setState({
      searchParams: {isProxy: temp},
      page: 0,
    },() => {
      let { searchForm } = this.state;
      let forms = [ 'keyWord', 'companyId', 'currencyCode', 'remark' ];
      searchForm.map(item => {
        if(~forms.indexOf(item.id)){
          delete item.defaultValue
        }
      });
      this.searchTag && this.searchTag.setValues({
        statusEnums: 'default'
      });
      this.getList()
    })
  };

  //点击行
  handleRowClick = (e,record) => {
    e.stopPropagation();
    e.preventDefault();
    configureStore.store.dispatch(setLoanSearch(cacheSearchData));
    this.context.router.push(this.state.loanDetail.url.replace(':formOID',record.formOid).replace(':loanBillOID',record.loanBillOid).replace(':backType','history'));
  };

  turnToRepayment = () => {
    const { editTransaction, info } = this.state;
    if(Object.keys(editTransaction).length === 0){
      message.error(messages('loan-billing.key115')/*请选择支付流水号*/);
      return -1;
    }
    info.stayWriteoffAmount = editTransaction.repaymentValue;
    info.transactionDetailId = editTransaction.transactionDetailId;
    info.transactionDetailCode = editTransaction.transactionDetailCode;
    this.setState({modalShow: false, info}, () => {
      this.setState({repayFrame: true});
    })
  };

  onSelectChange = selectedRowKeys => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    if(selected){
      this.setState({editTransaction: record});
    }
  };

  handleClose = value => {
    this.setState({repayFrame: false, info: {}},() => {
      if(typeof value === 'boolean' && value){
        this.getList();
      }
    });
  };

  handleView = record => {
    this.setState({ viewFrame: true, viewId: record.id });
  };

  handleViewRefund = item => {
    if (item.type === 2 || item.type === 3) {
      this.context.router.push(menuRoute.getRouteItem('expense-report-detail').url.replace(':expenseReportOID', item.expenseReportOid).replace(':pageFrom','my'));
    } else {
      this.setState({ refundFrame: true, refundParams: item.repaymentOid, historyModal: false });
    }
  };

  extendMoney = (e, value, record) => {
    e.stopPropagation();
    this.setState({
      extendMoneyFrame: true,
      viewId: record.id
    });
  };

  turnPermanent = (e, value, record) => {
    e.stopPropagation();
    this.setState({
      turnPermanentFrame: true,
      viewId: record.id
    });
  };

  handleExtendClose = (value) => {
    this.setState({extendMoneyFrame: false, info: {}},() => {
      // if(typeof value === 'boolean' && value){
        this.getList();
      // }
    });
  };

  handleTurnClose = (value) => {
    console.log("value", value)
    this.setState({turnPermanentFrame: false, info: {}},() => {
      // if(typeof value === 'boolean' && value){
        this.getList();
      // }
    });
  };

  changeAgentData = (isAgent, user) => {
    if (isAgent) {
      this.setState({
        agentUser: user,
        agendVisible: false
      }, () => {
        this.getList();
      })
    } else {
      this.setState({ agendVisible: false }, () => {
        this.getList();
      })
    }
  }

  render(){
    const { status, searchForm, pagination, data, columns, loading, repayFrame, info, modalShow, allLoading, transactionList,
      transactionColumns, rowSelection, historyModal, viewFrame, viewId, refundParams, historyId, refundFrame, extendMoneyFrame, turnPermanentFrame, agendVisible } = this.state;
    return(
      <Spin spinning={allLoading}>
      <div className='borrow-management'>
        <Tabs type="card" onChange={this.onChangeTabs} defaultActiveKey={status}>
          {this.renderTabs()}
        </Tabs>
        <SearchArea
          searchForm={searchForm}
          wrappedComponentRef={inst => this.searchTag = inst}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <div style={{margin:'10px 0px'}}>{messages('common.total', {total: pagination.total})/*共搜索到 {pagination.total} 条数据*/}</div>
        <ResizeTable
          rowKey="id"
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          size="middle"
          onRow={record => ({onClick: () => this.handleView(record)})}
        />
        <SlideFrame
          show={repayFrame}
          title={messages('loan-billing.key42')/*新建还款*/}
          key='repaymentLoan'
          content={repaymentContent}
          params={{info, repayFrame, loanRefund: false}}
          onClose={this.handleClose}
          afterClose={this.handleClose}
        />
        <Modal
          visible={modalShow}
          width={700}
          title={messages('loan-billing.key116')/*选择支付流水*/}
          onOk={this.turnToRepayment}
          onCancel={() => {
            this.setState({
              modalShow: false,
              editTransaction: {}
            })
          }}
        >
          <Row>
            <Col span={11}> {messages('loan-billing.key117')/*借款单号*/}：{transactionList[0] ? transactionList[0].businessCode : '-'}
            </Col>
            <Col span={12} offset={1}> {messages('loan-billing.key2')/*借款行号*/}：{transactionList[0] ? transactionList[0].sequence : '-'}
            </Col>
          </Row>
          <Row>
            <Col span={11}> {messages('loan-billing.key45')/*收款人*/}：{transactionList[0] ? transactionList[0].payeeName : '-'}
            </Col>
            <Col span={12} offset={1}> {messages('loan-billing.key12')/*借款类型*/}：{transactionList[0] ? transactionList[0].loanTypeName : '-'}
            </Col>
          </Row>
          <ResizeTable
            dataSource={transactionList}
            rowSelection={rowSelection}
            rowKey="transactionDetailId"
            columns={transactionColumns}
            bordered
          />
        </Modal>
        <ViewHistory
          visible={historyModal}
          id={historyId}
          handleViewRefund={this.handleViewRefund}
          close={() => this.setState({historyModal: false})}
        />
        <SlideFrame
          show={viewFrame}
          title={messages('loan-billing.key118')/*查看借款计划*/}
          key='viewLine'
          content={viewLine}
          params={{
            viewFrame,
            viewId
          }}
          onClose={() => {this.setState({viewFrame: false})}}
          afterClose={() => {this.setState({viewFrame: false})}}
        />
        <SlideFrame
          show={refundFrame}
          title={messages('loan-billing.key89')/*还款详情*/}
          key='refund'
          content={refundContent}
          params={{
            refundFrame,
            refundParams,
            location: this.props.location
          }}
          onClose={() => this.setState({refundFrame: false})}
          afterClose={() => this.setState({refundFrame: false})}
        />
        <SlideFrame
          show={extendMoneyFrame}
          title="延长还款"
          key='extendMoney'
          content={extendLoad}
          params={{
            extendMoneyFrame,
            mode: 'add',
            viewId,
            onClose: this.handleExtendClose
          }}
          onClose={this.handleExtendClose}
          afterClose={this.handleExtendClose}
        />
        <SlideFrame
          show={turnPermanentFrame}
          title="转永久"
          key='turnPermanent'
          content={turnPermanent}
          params={{
            turnPermanentFrame,
            mode: 'add',
            viewId,
            onClose: this.handleTurnClose
          }}
          onClose={this.handleTurnClose}
          afterClose={this.handleTurnClose}
        />
        <AgentModal
          visible={agendVisible}
          onChange={this.changeAgentData}
          dataList={this.state.dataList}
        />
      </div>
      </Spin>
    )
  }
}


LoanManagement.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    user: state.login.user,
    loanSearch: state.cache.loanSearch
  }
}

export default connect(mapStateToProps)(LoanManagement);
